package repository

import (
	"context"
	"database/sql"
	"strings"

	"mall/common/modelx"
	"mall/service/forum/model"

	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
)

type (
	// UserCollectRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customUserCollectRepository.
	UserCollectRepository interface {
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumUserCollect, int64, error) // ##25.03.11##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumUserCollect,
		) error
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumUserCollect,
		) error
		UpdateBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64, cols model.M) error
	}

	customUserCollectRepository struct {
		mysqlConn *sql.DB
	}
)

// NewUserCollectRepository returns a repository for the database table.
func NewUserCollectRepository(mysqlConn *sql.DB) UserCollectRepository {
	return &customUserCollectRepository{
		mysqlConn: mysqlConn,
	}
}

func (r *customUserCollectRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumUserCollect, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumUserCollectColumns.CollectID+" DESC"))
					mods = append(mods, model.ForumUserCollectWhere.CollectID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumUserCollectColumns.CollectID+" ASC"))
					mods = append(mods, model.ForumUserCollectWhere.CollectID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumUserCollectColumns.CollectID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserCollectColumns.CollectID, opMap)...)
		case model.ForumUserCollectColumns.UserID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserCollectColumns.UserID, opMap)...)
		case model.ForumUserCollectColumns.PlatformID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserCollectColumns.PlatformID, opMap)...)
		case model.ForumUserCollectColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserCollectColumns.ObjectID, opMap)...)
		case model.ForumUserCollectColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ForumUserCollectColumns.ObjectType, opMap)...)
		case model.ForumUserCollectColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.ForumUserCollectColumns.Status, opMap)...)
		case model.ForumUserCollectColumns.CreatedAt:
			mods = append(mods, modelx.GetTimeMods(model.ForumUserCollectColumns.CreatedAt, opMap)...)
		case model.ForumUserCollectColumns.UpdatedAt:
			mods = append(mods, modelx.GetTimeMods(model.ForumUserCollectColumns.UpdatedAt, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumUserCollects(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ForumUserCollectColumns.CollectID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumUserCollects(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customUserCollectRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumUserCollect,
) error {
	var db boil.ContextExecutor = r.mysqlConn
	if tx != nil {
		db = tx
	}

	return data.Insert(ctx, db, boil.Infer())
}

func (r *customUserCollectRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumUserCollect,
) error {
	var db boil.ContextExecutor = r.mysqlConn
	if tx != nil {
		db = tx
	}

	_, err := data.Update(ctx, db, boil.Blacklist(
		model.ForumUserCollectColumns.CollectID,
		model.ForumUserCollectColumns.UserID,
		model.ForumUserCollectColumns.PlatformID,
		model.ForumUserCollectColumns.CreatedAt,
	))
	if err != nil {
		return err
	}

	return nil
}

func (r *customUserCollectRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) error {
	if len(ids) > 0 {
		var db boil.ContextExecutor = r.mysqlConn
		if tx != nil {
			db = tx
		}

		var mods []qm.QueryMod
		mods = append(mods, model.ForumUserCollectWhere.CollectID.IN(ids))

		rowsAff, err := model.ForumUserCollects(mods...).UpdateAll(ctx, db, cols)
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}
	}

	return nil
}
